<template>
  <div id="app">
    <div class="container">
      <!-- 顶部导航 -->
      <div class="header">
        <div class="logo">
          <i class="fas fa-play-circle"></i>
          Bilili视频平台
        </div>
        <div class="user-actions">
          <router-link to="/" class="btn btn-primary float-end"
                       style="background-color: #FB7299; border-color: #FB7299; margin-left: 10px ;margin-right: 10px;">
            <i class="fas fa-cog"></i> 主页
          </router-link>
          <router-link to="/login" class="btn btn-primary float-end"
                       style="background-color: #FB7299; border-color: #FB7299;" @click="userstore.logout()">
            登出
          </router-link>
        </div>
      </div>

      <!-- 用户信息卡片 -->
      <div class="creator-header">
        <div>
          <img :src="userInfo.pic" class="creator-avatar" alt="我的头像">
        </div>

        <div class="user-info">
          <h1 class="username">{{ userInfo.name }}</h1>
          <div class="user-level">Lv.{{ userInfo.level }} 正式会员
          </div>

          <div class="user-stats1">
            <div class="stat-card">
              <div class="stat-value">{{ formatNumber(userInfo.followers) }}</div>
              <div class="stat-label">粉丝</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ formatNumber(userInfo.like_up) }}</div>
              <div class="stat-label">关注用户</div>
            </div>
            <div class="stat-card">
              <div class="stat-value">{{ formatNumber(userInfo.like_video) }}</div>
              <div class="stat-label">关注视频</div>
            </div>
          </div>
        </div>
      </div>


      <div class="content-row">
        <div class="interaction-history">
          <h2 class="section-title">
            <i class="fas fa-history"></i> 互动历史
          </h2>
          <div class="history-tabs">
            <div
                v-for="tab in tabs"
                :key="tab.id"
                class="history-tab"
                :class="{ active: activeTab === tab.id }"
                @click="activeTab = tab.id"
            >
              <i class="fas" :class="tab.icon"></i>
              <span>{{ tab.name }}</span>
            </div>
          </div>

          <div class="content">
            <div v-if="isLoading" class="loading">
              <i class="fas fa-spinner fa-spin"></i> 加载中...
            </div>

            <div v-if="error" class="error">
              <i class="fas fa-exclamation-triangle"></i> {{ error }}
            </div>

            <div v-if="!isLoading && !error && isEmpty" class="empty">
              暂无{{ tabs.find(t => t.id === activeTab)?.name || '数据' }}
            </div>

            <!-- 点赞/投币历史列表 -->
            <div v-if="!isLoading && !error && !isEmpty && (activeTab === 'like' || activeTab === 'coin')"
                 class="video-list">
              <div
                  v-for="item in currentContent"
                  :key="item.bvid"
                  class="video-item"
              >

                <div class="video-cover-container">
                  <img :src="item.pic" class="video-cover" alt="视频封面">
                </div>

                <div class="video-info">
                  <h3 class="video-title">{{ item.title }}</h3>
                  <div class="video-meta">
                    <span class="views"><i class="fas fa-eye"></i> {{ formatNumber(item.views) }}</span>
                    <span class="likes"><i class="fas fa-heart"></i> {{ formatNumber(item.likes) }}</span>
                  </div>
                  <div class="video-date"><i class="far fa-clock"></i> {{ item.date }}</div>
                </div>
              </div>
            </div>

            <!-- 已关注用户列表 -->
            <div v-if="!isLoading && !error && !isEmpty && activeTab === 'users'" class="user-row">
              <div
                  v-for="user in currentContent"
                  :key="user.mid"
                  class="user-card"
              >
                <div class="user-avatar-container">
                  <img :src="user.pic" class="user-avatar" alt="用户头像">
                  <div v-if="user.following" class="mutual-badge">互关</div>
                </div>
                <div class="user-details">
                  <h3 class="user-name">{{ user.name }}</h3>
                  <div class="user-stats">
                    <span><i class="fas fa-users"></i> {{ formatNumber(user.followers) }}</span>
                    <span><i class="fas fa-video"></i> {{ user.videos }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 已关注视频列表 -->
            <div v-if="!isLoading && !error && !isEmpty && activeTab === 'videos'" class="video-list">
              <div
                  v-for="video in currentContent"
                  :key="video.bvid"
                  class="video-item"
              >
                <img :src="video.pic" class="video-cover" alt="视频封面">
                <div class="video-info">
                  <h3 class="video-title">{{ video.title }}</h3>
                  <div class="video-meta">
                    <span class="views"><i class="fas fa-eye"></i> {{ formatNumber(video.views) }}</span>
                    <span class="likes"><i class="fas fa-heart"></i> {{ formatNumber(video.likes) }}</span>
                  </div>
                  <div class="video-date"><i class="far fa-clock"></i> {{ video.date }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 兴趣词云 -->
        <div class="interest-cloud">
          <h2 class="section-title">
            <i class="fas fa-cloud"></i> 兴趣词云
          </h2>
          <p>根据您的观看和互动历史生成的关键词分析</p>

          <div class="wordcloud-container">
            <div class="wordcloud-title">您的兴趣关键词</div>
            <div ref="wordcloud"></div>
          </div>
        </div>
      </div>
    </div>
    <router-view :key="$route.fullPath" />
  </div>

</template>


<script setup>
import {ref, computed, onMounted} from 'vue'
import {useUserStore} from "@/store/user.js";
import {getLike, getMeBasicInfo, getMeVideoCoin, getMeVideoLike, getUpBasicInfo} from "@/api/user.js";
import {getVideoBasicInfo} from "@/api/video.js";

const userstore = useUserStore();

const userInfo = ref({
  name: "加载中",
  level: 0,
  followers: 0,
  like_up: 0,
  like_video: 0,
  pic: null
})


const followingUsers = ref([])
const followingVideos = ref([])
const coinHistory = ref([])
const likeHistory = ref([])

const isLoading = ref(false)
const error = ref(null)


const tabs = [
  {id: 'like', name: '点赞历史', icon: 'fa-heart'},
  {id: 'coin', name: '投币历史', icon: 'fa-coins'},
  {id: 'users', name: '已关注用户', icon: 'fa-user'},
  {id: 'videos', name: '已关注视频', icon: 'fa-video'}
]
const activeTab = ref("like")


const initUserInfo = async () => {
  try {
    const response = await getMeBasicInfo();
    const userData = response.data;

    userInfo.value = {
      name: userData.data.name || '未命名用户',
      followers: userData.data.followers || 0,
      pic: '/api/proxy/img?url=' + userData.data.pic,
      level: userData.data.level || 1,
    };

    return true;
  } catch (error) {
    console.error('请求用户信息失败:', error);

    userInfo.value = {
      name: '获取失败',
      followers: 0,
      pic: '/default-avatar.jpg'
    };
    return false;
  }
};

//获取用户关注up和视频的信息
const initLike = async () => {
  try {
    const respond = await getLike(userstore.uid);
    const res = respond.data;
    userInfo.value.like_up = 0 || res.data.mids.length;
    userInfo.value.like_video = res.data.bvids.length || 0;


    if (userInfo.value.like_up) {
      const userPromises = res.data.mids.map(async mid => {
        try {
          const userResponse = await getUpBasicInfo(mid);
          const userRes = await userResponse.data;
          return {
            mid,
            name: userRes.name || '未知用户',
            pic: '/api/proxy/img?url=' + userRes.pic || '/default-avatar.jpg',
            following: userRes.following,
            videos: userRes.videos,
            views: userRes.views,
            followers: userRes.followers,
            likes: userRes.likes
          };
        } catch (err) {
          console.error(`获取用户 ${mid} 信息失败:`, err);
          return {
            mid,
            name: `用户${mid}`,
            avatar: '/default-avatar.jpg',
            sign: '获取信息失败',
            followers: 0
          };
        }
      });
      followingUsers.value = await Promise.all(userPromises);
    }

    if (userInfo.value.like_video) {
      const videoPromises = res.data.bvids.map(async (bvid) => {
        try {
          const response = await getVideoBasicInfo(bvid);
          const item = await response.data;
          const date = new Date(item.pubdate * 1000)

          return {
            bvid: item.data.bvid,
            title: item.data.title,
            views: item.data.view,
            likes: item.data.like,
            date: date.toLocaleString(),
            pic: '/api/proxy/img?url=' + item.data.pic,
          };

        } catch (err) {
          console.error(`获取视频 ${bvid} 信息失败:`, err);
          return {
            bvid,
            title: `视频${bvid}`,
            cover: '/default-cover.jpg',
            desc: '获取信息失败',
            duration: 0,
            view: 0,
            like: 0,
            pubdate: 0
          };
        }
      });
      followingVideos.value = await Promise.all(videoPromises);
    }

  } catch (error) {
    console.error('请求失败:', error);
    error.value = '获取关注数据失败';
  }
}

// 获取coin,like历史数据
const fetchInteractionHistory = async () => {
  try {
    isLoading.value = true
    error.value = null
    const [coinRespond, likeRespond] = await Promise.all([
      getMeVideoCoin(),
      getMeVideoLike()
    ])
    const coinRes = coinRespond.data
    const likeRes = likeRespond.data

    coinHistory.value = (coinRes.data || []).map((item) => {
      const date = new Date(item.pubdate * 1000);

      return {
        bvid: item.bvid,
        title: item.title,
        views: item.view,
        likes: item.like,
        date: date.toLocaleString(),
        pic: '/api/proxy/img?url=' + item.pic,
      }
    })

    likeHistory.value = (likeRes.data || []).map((item) => {
      const date = new Date(item.pubdate * 1000);
      return {
        bvid: item.bvid,
        title: item.title,
        views: item.view,
        likes: item.like,
        date: date.toLocaleString(),
        pic: '/api/proxy/img?url=' + item.pic,
      }
    })

  } catch (err) {
    console.error('获取交互历史失败:', err)
    error.value = '获取交互历史失败'
  } finally {
    isLoading.value = false
  }
}


const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K';
  }
  return "" + num;
};

// 当前显示的内容
const currentContent = computed(() => {
  switch (activeTab.value) {
    case 'like':
      return likeHistory.value
    case 'coin':
      return coinHistory.value
    case 'users':
      return followingUsers.value
    case 'videos':
      return followingVideos.value
    default:
      return []
  }
})

// 当前内容是否为空
const isEmpty = computed(() => currentContent.value.length === 0)

onMounted(async () => {
  const success = await initUserInfo();
  if (success) {
    console.log('用户信息初始化成功');
    await initLike();
    await fetchInteractionHistory();
  } else {

  }
});

</script>


<style scoped>
:root {
  --primary: #4361ee;
  --primary-light: #4895ef;
  --secondary: #3f37c9;
  --accent: #f72585;
  --success: #4cc9f0;
  --dark: #2b2d42;
  --light: #f8f9fa;
  --gray: #8d99ae;
  --card-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

body {
  background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
  color: #333;
  min-height: 100vh;
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px 0;
  position: relative;
  border-bottom: 2px solid rgba(67, 97, 238, 0.1); /* 底部浅色分隔线 */
}

.header::after {
  content: "";
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 150px;
  height: 3px;
}

.logo {
  font-size: 2.2rem;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 12px;
  background: linear-gradient(135deg, var(--primary), var(--accent));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  position: relative;
  padding: 0 10px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.logo:hover {
  transform: translateY(-2px);
  text-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
}


.user-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}


.user-avatar {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e0e7ff 0%, #d1e3ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 60px;
  font-weight: bold;
  color: var(--primary);
  border: 4px solid var(--primary-light);
  box-shadow: 0 10px 30px rgba(67, 97, 238, 0.25);
  transition: var(--transition);
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 15px 35px rgba(67, 97, 238, 0.35);
}


.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 42px;
  font-weight: 800;
  margin-bottom: 10px;
  background: linear-gradient(135deg, var(--primary), var(--dark));
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.user-level {
  display: inline-block;
  background: linear-gradient(135deg, var(--primary), var(--secondary));
  color: white;
  padding: 6px 0;
  border-radius: 50px;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 25px;
  text-align: center;
}

.user-stats {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 30px;
  background: #f7faff;
  border-radius: 20px;
  min-width: 150px;
  border: 1px solid #e6f0ff;
  box-shadow: 0 5px 15px rgba(67, 97, 238, 0.1);
  transition: var(--transition);
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 25px rgba(67, 97, 238, 0.2);
}

.stat-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: var(--primary);
}

.stat-value {
  font-size: 36px;
  font-weight: 800;
  color: var(--accent);
  margin-bottom: 5px;
}

.stat-label {
  font-size: 16px;
  color: var(--gray);
  font-weight: 600;
}


.content-row {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  width: 100%;
  height:70vh;
}

.interaction-history, .interest-cloud {
  flex: 0 0 calc(50% - 15px);
  background: white;
  border-radius: 24px;
  box-shadow: var(--card-shadow);
  padding: 35px;
  border: 1px solid #e6f0ff;
  transition: var(--transition);
}

.interaction-history {
  flex: 7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.interest-cloud {
  flex: 5;
  height: 100%;
}

.interaction-history:hover, .interest-cloud:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 28px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f4ff;
  color: var(--primary);
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 700;
}

.section-title i {
  font-size: 24px;
  background: linear-gradient(135deg, var(--primary), var(--accent));
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}


/* 互动历史 */
.history-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

.history-tab {
  padding: 12px 25px;
  background: #f0f7ff;
  border-radius: 30px;
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
  border: 1px solid #d1e3ff;
}

.history-tab:hover, .history-tab.active {
  background: linear-gradient(135deg, var(--primary), var(--secondary));
  color: white;
  border-color: transparent;
}

.video-list {
  overflow-y: auto;
  gap: 16px;
  max-height: 45vh;
  padding-right: 10px;
  width: 100%;
}

.video-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-radius: 6px;
  transition: all 0.2s;
  border: 1px solid #eee;
  width: 100%;
}

.video-item:hover {
  border-color: #FB7299;
  box-shadow: 0 2px 8px rgba(251, 114, 153, 0.2);
}
.video-cover-container {
  position: relative;
  flex-shrink: 0;
}

.video-cover {
  width: 120px;
  height: 70px;
  border-radius: 4px;
  object-fit: cover;
}

.video-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.video-title {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.video-date {
  font-size: 12px;
  color: #999;
}

.user-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 8px;
  overflow-x: auto;
  white-space: nowrap;
}

.user-card {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  min-width: 180px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid #eee;
  white-space: normal;
}

.user-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(251, 114, 153, 0.15);
  border-color: #FB7299;
}

.user-avatar-container {
  position: relative;
  margin-bottom: 8px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.mutual-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  background: #FB7299;
  color: white;
  padding: 2px 6px;
  border-radius: 12px;
  font-size: 12px;
  line-height: 1;
}

.user-details {
  text-align: center;
  width: 100%;
}

.user-name {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #222;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100px;
}

.user-stats1 {
  display: flex;
  justify-content: left;
  gap: 80px;
  font-size: 12px;
  margin-left: 50px;
  align-items: center;
}

/* 词云区域 */
.wordcloud-container {
  width: 100%;
  height: 350px;
  background: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  border: 1px solid #e6f0ff;
  margin-top: 20px;
}

.wordcloud-title {
  position: absolute;
  top: 25px;
  left: 25px;
  font-size: 18px;
  font-weight: 700;
  color: var(--primary);
  z-index: 10;
}

@media (max-width: 1200px) {
  .content-row {
    flex-direction: row;
    height: auto; /* 改为自动高度 */
    min-height: 500px; /* 设置最小高度 */
  }

  .interaction-history, .interest-cloud {
     flex: 0 0 100%;
    height: 400px;
   }
  .user-stats {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 20px;
  }

  .user-row {
    gap: 12px;
    padding-bottom: 8px;
  }

  .user-card {
    min-width: 100px;
    padding: 8px;
  }

  .user-avatar {
    width: 50px;
    height: 50px;
  }

  .user-name {
    font-size: 13px;
    max-width: 80px;
  }

  .user-stats {
    gap: 8px;
    font-size: 11px;
  }
  .video-list{
    grid-template-columns: 1fr;
  }
}

</style>
